package site.brood.common.exception;


import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import site.brood.common.core.str.StrUtil;
import site.brood.common.core.exception.ServiceException;
import site.brood.common.core.web.AjaxJson;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * 全局异常拦截
 * 注意：
 * 1）此处一定要用@RestControllerAdvice，不能用@ControllerAdvice
 * 否则，报错：Circular view path
 * 2）在启动类上要加scanBasePackages = "site.brood"作用：扫描此包下的全局异常处理类
 * 否则不会走此异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public AjaxJson handleServiceException(ServiceException e, HttpServletRequest request)
    {
        logError(e,request);
        return AjaxJson.error(e.getCode(),e.getMessage());
    }

    /**
     * 拦截sql异常
     */
    @ExceptionHandler(SQLException.class)
    public AjaxJson handleSQLException(SQLException e, HttpServletRequest request){
        // 无论是否打开隐藏sql，日志表记录的都是真实异常信息
        logErrorCause(e,request);
        return AjaxJson.errorByMessage(e.getMessage());
    }

    /**
     * 自定义验证异常
     * form表单参数校验异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxJson handleBindException(BindException e)
    {
        log.error(e.getMessage(), e);
        // 输出参数名及值
        String message = e.getFieldErrors().stream().map(ex-> ex.getField()+":"+ex.getDefaultMessage())
                .reduce("",(s1,s2)->s1+"\n"+s2);
        return AjaxJson.errorByMessage(message);
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxJson handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                        HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        StrUtil.format("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return AjaxJson.errorByMessage(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxJson handleRuntimeException(RuntimeException e, HttpServletRequest request)
    {
        logError(e, request);
        return AjaxJson.errorByMessage(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxJson handleException(Exception e, HttpServletRequest request)
    {
        logError(e, request);
        return AjaxJson.errorByMessage(e.getMessage());
    }

    private void logError(Exception e, HttpServletRequest request){
        // 打印堆栈，以供调试
        log.warn("-----全局异常处理---------------");
        System.out.println("-----全局异常处理---------------");
        e.printStackTrace();
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常:{}", requestURI, e);
    }

    private void logErrorCause(Exception e, HttpServletRequest request){
        // 打印堆栈，以供调试
        log.warn("-----全局异常处理---------------");
        System.out.println("-----全局异常处理---------------");
        e.printStackTrace();
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常:{}", requestURI, e.getCause());
    }

    private void logErrorByMessage(String message, HttpServletRequest request){
        // 打印堆栈，以供调试
        log.warn("-----全局异常处理---------------");
        System.out.println("-----全局异常处理---------------");
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常:{}", requestURI, message);
    }
}
